import React, { useState, useRef, forwardRef, useImperativeHandle, ReactNode } from 'react';
import classNames from 'classnames';
import { Button } from 'antd-mobile';
// import { Input } from './InputCore';
import { Input } from 'antd-mobile';
import { InputRef, InputProps } from 'antd-mobile/es/components/input';
import { NativeProps, withNativeProps } from 'antd-mobile/es/utils/native-props';
import { mergeProps } from 'antd-mobile/es/utils/with-default-props';
import { SearchOutline } from 'antd-mobile-icons';
import { usePropsValue } from 'antd-mobile/es/utils/use-props-value';
import { useConfig } from 'antd-mobile/es/components/config-provider';
import { getMessage } from '@inbiz/react';
import 'antd-mobile/es/components/search-bar/search-bar.css';

const classPrefix = `adm-search-bar`;

export type SearchBarRef = InputRef;

export type SearchBarProps = Pick<InputProps, 'onFocus' | 'onBlur' | 'onClear'> & {
  value?: string;
  defaultValue?: string;
  maxLength?: number;
  placeholder?: string;
  clearable?: boolean;
  showCancelButton?: boolean | ((focus: boolean, value: string) => boolean);
  cancelText?: string;
  icon?: ReactNode;
  clearOnCancel?: boolean;
  onSearch?: (val: string) => void;
  onChange?: (val: string) => void;
  onCancel?: () => void;
  autoFocus?: boolean;
  disabled?: boolean;
  readOnly?: boolean;
  onClick?: (e: any) => void;
  cancelColor?: string;
} & NativeProps<
    '--background' | '--border-radius' | '--placeholder-color' | '--height' | '--padding-left'
  >;

const defaultProps = {
  clearable: true,
  showCancelButton: false,
  defaultValue: '',
  clearOnCancel: true,
  icon: <SearchOutline />,
  disabled: false,
  readOnly: false,
};

export const SearchBar = forwardRef<SearchBarRef, SearchBarProps>((p, ref) => {
  const { locale } = useConfig();
  const props = mergeProps(
    defaultProps,
    {
      cancelText: locale.common.cancel,
    },
    p,
  );
  const [value, setValue] = usePropsValue(props);
  const [hasFocus, setHasFocus] = useState(false);
  const inputRef = useRef<InputRef>(null);

  useImperativeHandle(ref, () => ({
    clear: () => inputRef.current?.clear(),
    focus: () => inputRef.current?.focus(),
    blur: () => inputRef.current?.blur(),
  }));

  const renderCancelButton = () => {
    let isShowCancel = false;
    if (typeof props.showCancelButton === 'function') {
      isShowCancel = props.showCancelButton(hasFocus, value);
    } else {
      isShowCancel = props.showCancelButton && hasFocus;
    }

    return (
      isShowCancel && (
        <div
          className={`${classPrefix}-suffix`}
          onMouseDown={(e) => {
            e.preventDefault();
          }}
          onTouchStart={(e) => {
            e.preventDefault();
          }}
        >
          <Button
            fill="none"
            className={`${classPrefix}-cancel-button`}
            style={{
              pointerEvents: 'auto',
              fontSize: 16,
              color: props?.cancelColor || 'var(--inbiz-color-text)',
            }}
            onClick={() => {
              if (props.clearOnCancel) {
                inputRef.current?.clear?.();
              }
              inputRef.current?.blur?.();
              props.onCancel?.();
            }}
          >
            {props.cancelText}
          </Button>
        </div>
      )
    );
  };

  return withNativeProps(
    props,
    <div
      className={classNames(classPrefix, {
        [`${classPrefix}-active`]: hasFocus,
      })}
    >
      <div className={`${classPrefix}-input-box`} onClick={props.onClick}>
        {props.icon && <div className={`${classPrefix}-input-box-icon`}>{props.icon}</div>}
        <Input
          ref={inputRef}
          className={classNames(`${classPrefix}-input`, {
            [`${classPrefix}-input-without-icon`]: !props.icon,
          })}
          value={value}
          onChange={setValue}
          maxLength={props.maxLength}
          placeholder={props.placeholder || getMessage('WapSearchBar.search')}
          clearable={props.clearable}
          onFocus={(e) => {
            setHasFocus(true);
            props.onFocus?.(e);
          }}
          onBlur={(e) => {
            setHasFocus(false);
            props.onBlur?.(e);
          }}
          onClear={props.onClear}
          type="search"
          enterKeyHint="search"
          onEnterPress={() => {
            // inputRef.current?.blur();
            props.onSearch?.(value);
          }}
          autoFocus={props.autoFocus}
          disabled={props.disabled}
          readOnly={props.readOnly}
        />
      </div>
      {renderCancelButton()}
    </div>,
  );
});
